﻿using UnityEngine;
using UnityEditor;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;

public class mTest2 : AssetPostprocessor
{
    public static string FBX_FrameConfigAssetPath = "Assets/test2/test2_frameConfig.txt";
    public void OnPostprocessModel(GameObject go)
    {
        Debug.Log(assetPath);

        ///Get frame config
        ///run:0-20
        ///idle:21-31
        ///charge:32-42
        ///attack:43-58
        ///dead:59-75
        TextAsset textAsset = AssetDatabase.LoadAssetAtPath(FBX_FrameConfigAssetPath, typeof(TextAsset)) as TextAsset;
        string[] configs = textAsset.text.Split(new string[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries);

        ///Model importer lets you modify model import settings from editor scripts.
        ModelImporter modelImporter = assetImporter as ModelImporter;

        List<ModelImporterClipAnimation> clips = new List<ModelImporterClipAnimation>();
        foreach (string curConfig in configs)
        {
            clips.Add(ParseAnimationClip(curConfig));
        }

        modelImporter.clipAnimations = clips.ToArray();

        ///Import any changed assets.
        ///Call OnPostprocessModel twice cause call once nerver split 
        AssetDatabase.Refresh();
    }


    static ModelImporterClipAnimation ParseAnimationClip(string curConfig)
    {
        ///run:0-20
        string clipName = curConfig.Split(":"[0])[0];
        string length = curConfig.Split(":"[0])[1];


        /// 0-20
        int startIndex = int.Parse(length.Split("-"[0])[0]);
        int endIndex = int.Parse(length.Split("-"[0])[1]);

        ModelImporterClipAnimation clip = new ModelImporterClipAnimation();
        clip.firstFrame = Convert.ToSingle(startIndex);
        clip.lastFrame = Convert.ToSingle(endIndex);
        clip.loopTime = true;
        clip.name = clipName;

        return clip;
    }
}
